package org.springframework.web.servlet.study;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.logging.ConsoleHandler;

public class Study {

  public static void main(String[] args) throws LifecycleException, UnsupportedEncodingException {
	  // 强制tomcat JUL编码为UTF-8
	  var rootLogger = java.util.logging.Logger.getLogger("");
	  for (var handler : rootLogger.getHandlers()) {
		  if (handler instanceof ConsoleHandler ch) {
			  ch.setEncoding("UTF-8");
		  }
	  }

	  Tomcat tomcat = new Tomcat();
	  tomcat.setPort(8080);
	  tomcat.getConnector();

	  Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());

	  // 先创建 WebApplicationContext
	  AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	  context.register(AppConfig.class);
	  context.setServletContext(ctx.getServletContext()); // ⚠ 关键步骤：设置 ServletContext
	  context.refresh();

	  DispatcherServlet dispatcherServlet = new DispatcherServlet(context);

	  Tomcat.addServlet(ctx, "dispatcher", dispatcherServlet);
	  ctx.addServletMappingDecoded("/", "dispatcher");

	  tomcat.start();
	  tomcat.getServer().await();
  }
}
